import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {Checkbox, Form, Input, Modal, Row, Col} from 'antd';

@connect(state => ({
  employee: state.employee,
}))
@Form.create()
export default class RoleModal extends PureComponent {

  state = {
    checkedValues: []
  }

  componentDidMount() {
    const _this = this;
    const {dispatch, items, modalVisible} = this.props;
    if(modalVisible){
      dispatch({
        type: 'employee/queryEmployeeRole',
        payload: {userId: items.id},
        callback: (result) => {
          _this.setState({checkedValues: result.rows})
        }
      });
    }
  }

  handleOk = () => {
    const {checkedValues} = this.state;
    const {form, handleSave} = this.props;
    form.validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return
      }
      values.roles = checkedValues;
      handleSave(values, form);
    })
  }

  onChangeOne = (checkedValues) => {
    this.setState({
      checkedValues:checkedValues
    })
  };

  render() {
    const {checkedValues} = this.state;
    const {form: {getFieldDecorator}, items, modalVisible, handleModalCancel, roleList} = this.props;

    let options = [];
    if(roleList){
      roleList.map(obj=>{
        options.push({label:obj.name+'('+obj.code+')', value:obj.id});
      })
    }

    return (
      <div>
        <Modal
          title='角色'
          visible={modalVisible}
          onOk={this.handleOk}
          onCancel={handleModalCancel}
          closable={false}
        >
          <Form>
            {getFieldDecorator('id', {
              initialValue: items.id,
            })(
              <Input hidden={true}/>
            )}
            <Checkbox.Group value={checkedValues} onChange={this.onChangeOne} style={{width:'100%'}}>
              <Row>
                {options.map(obj=><Col span={8}><Checkbox value={obj.value} key={obj.value}>{obj.label}</Checkbox></Col>)}
              </Row>
            </Checkbox.Group>
          </Form>
        </Modal>
      </div>
    );
  }
}
